import requests
import time
from bs4 import BeautifulSoup
from http import cookiejar

headers = {
    "Host":"www.zhihu.com",
    "Referer":"https://www.zhihu.com/",
    "User-Agent":"Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36"}


session = requests.session()

#登录cookie信息
session.cookies = cookiejar.LWPCookieJar(filename='cookies.txt')
try:
    print(session.cookies)
    session.cookies.load(ignore_discard=True)
except:
    print('没有cookie 信息')
   
def get_xsrf():
    response = session.get("https://www.zhihu.com/",headers=headers)
    soup = BeautifulSoup(response.content,'html.parser')
    xsrf = soup.find('input',attrs={"name":"_xsrf"}).get("value")
    return xsrf

def get_captcha():
    t = str(int(time.time()*1000))
    captcha_url = 'https://www.zhihu.com/captcha.gif?r=' + t + '&type=login'
    r = session.get(captcha_url,headers=headers)
    with open('captcha.jpg','wb') as f:
        f.write(r.content)
    captcha = input("验证码：")
    return captcha

def login(phone_num, password):
    login_url = 'https://www.zhihu.com/login/phone_num'
    data ={
        '_xsrf':get_xsrf(),
        'password':password,
        'phone_num':phone_num,
        'captcha':get_captcha()
        }
    response = session.post(login_url,data=data,headers=headers)
    login_code = response.json()
    print(login_code['msg'])
    for i in session.cookies:
        print(i)
    session.cookies.save()

if __name__ == "__main__":
    phone_num = '***'
    password = '***'
    login(phone_num,password)

    
    


